package cn.sh.yhk.service.basic.impl;

import cn.sh.yhk.configure.enums.UserState;
import cn.sh.yhk.mapper.basic.SCommonConfigMapper;
import cn.sh.yhk.mapper.basic.SMenuMapper;
import cn.sh.yhk.mapper.basic.SRoleMapper;
import cn.sh.yhk.mapper.basic.SUserMapper;
import cn.sh.yhk.model.basic.SCommonConfigExample;
import cn.sh.yhk.model.basic.SRole;
import cn.sh.yhk.model.basic.SUser;
import cn.sh.yhk.model.basic.SUserExample;
import cn.sh.yhk.service.basic.RoleService;
import cn.sh.yhk.service.basic.UserService;
import cn.sh.yhk.utils.DateUtils;
import cn.sh.yhk.utils.Md5Utils;
import cn.sh.yhk.utils.UUIDUtils;
import cn.sh.yhk.vo.BasicVo;
import cn.sh.yhk.vo.SRoleVo;
import cn.sh.yhk.vo.SUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    private static String DEFAULR_PASSWORD = "default_password";
    @Resource
    SUserMapper sUserMapper;

    @Resource
    SRoleMapper sRoleMapper;

    @Resource
    SMenuMapper sMenuMapper;

    @Resource
    RoleService roleService;

    @Resource
    SCommonConfigMapper sCommonConfigMapper;


    public static void main(String[] args) {

    }

    private List<SRoleVo> getMenuByRole(List<SRole> roles) {
        List<SRoleVo> sRoleVos = new ArrayList<>();
        for (SRole role : roles) {
            SRoleVo sRoleVo = new SRoleVo();
            BeanUtils.copyProperties(role, sRoleVo);
            sRoleVo.setMenuList(sMenuMapper.selectMenuByRoleId(role.getId().longValue()));
            sRoleVos.add(sRoleVo);
        }
        return sRoleVos;
    }

    @Override
    public BasicVo login(SUser sUser) {
        SUserExample ex = new SUserExample();
        ex.createCriteria().andUserNameEqualTo(sUser.getUserName());
        ex.or().andUserAccountEqualTo(sUser.getUserName());
        List<SUser> ulist = sUserMapper.selectByExample(ex);
        if (ulist.size() == 0) {
            return BasicVo.fail("用户名不存在");
        }
        ex.clear();
        ex.createCriteria().andUserNameEqualTo(sUser.getUserName());
        ex.or().andUserAccountEqualTo(sUser.getUserName());
        SUser user = ulist.get(0);
        String pwd = Md5Utils.hash(Md5Utils.hash(sUser.getPassword()));
        if (!pwd.equals(user.getPassword())) {
            return BasicVo.fail("密码不正确");
        }
        SUserVo sUserVo = new SUserVo();
        BeanUtils.copyProperties(user, sUserVo);
        List<SRole> roleList = sRoleMapper.selectRoleByUserId(user.getUserId());
        List<SRoleVo> sRoleVoList = new ArrayList<SRoleVo>();
        getMenuByRole(roleList);
        sUserVo.setRoleVoList(sRoleVoList);
        return BasicVo.success("登录成功", sUserVo);
    }

    @Override
    public SUserVo securityLogin(String userName) {
        SUserExample ex = new SUserExample();
        ex.createCriteria().andUserNameEqualTo(userName);
        List<SUser> users = sUserMapper.selectByExample(ex);
        if (users.size() <= 0) {
            return null;
        } else {
            SUser user = users.get(0);
            SUserVo sUserVo = new SUserVo();
            BeanUtils.copyProperties(user, sUserVo);
            List<SRole> roleList = sRoleMapper.selectRoleByUserId(user.getUserId());
            List<SRoleVo> sRoleVoList = new ArrayList<SRoleVo>();
            sUserVo.setRoleVoList(getMenuByRole(roleList));
            SUser upuser = new SUser();
            upuser.setLastLoginTimestamp(new Date());
            sUserMapper.updateByExampleSelective(upuser, ex);
            return sUserVo;
        }
    }

    @Override
    public BasicVo getUser(Long userId) {
        SUserExample sUserExample = new SUserExample();
        sUserExample.createCriteria().andUserIdEqualTo(userId);
        SUser sUser = sUserMapper.selectByExample(sUserExample).get(0);
        SUserVo sUserVo = new SUserVo();
        BeanUtils.copyProperties(sUser, sUserVo);

        sUserVo.setRoleVoList((List<SRoleVo>) roleService.getList(userId).getObject());
        if (null != sUser) {
            return BasicVo.success("请求成功", sUserVo);
        } else {
            return BasicVo.fail("请求成功");
        }

    }

    @Override
    public BasicVo createUser(SUserVo userVo, String groups, String menus) {
        SUserExample ex = new SUserExample();
        //查看用户是否已存在
        ex.createCriteria().andUserNameEqualTo(userVo.getUserName());
        ex.or().andUserAccountEqualTo(userVo.getUserName());
        if (sUserMapper.selectByExample(ex).size() > 0) {
            return BasicVo.fail("用户名已存在");
        }
        //密码盐
        SCommonConfigExample confex = new SCommonConfigExample();
        confex.createCriteria().andParameterEqualTo(DEFAULR_PASSWORD);
        String pwd = Md5Utils.hash(sCommonConfigMapper.selectConfigByExample(confex).getValue());
        String salt = UUIDUtils.getUUID();
        userVo.setUserAccount(userVo.getUserName());
        userVo.setPassword(Md5Utils.hash(Md5Utils.hash(pwd + salt)));
        userVo.setActivity(UserState.ACTIVITY_ENABLED.getName());
        userVo.setCreateAccount(userVo.getCreateAccount() == null ? "admin" : userVo.getCreateAccount());
        userVo.setModifyAccount(userVo.getModifyAccount() == null ? "admin" : userVo.getModifyAccount());
        userVo.setCreateTimestamp(DateUtils.getNow());
        if (sUserMapper.insert(userVo) > 0) {
            if (groups != null) {
                for (String groupId : groups.split(",")) {
                    sUserMapper.insertUserGroup(userVo.getUserId(), new Long(groupId));
                }
            }
            if (menus != null) {
                for (String menuId : menus.split(",")) {
                    sUserMapper.insertUserMenu(userVo.getUserId(), new Long(menuId));
                }
            }
            return BasicVo.success("请求成功");
        } else {
            return BasicVo.fail("请求失败");
        }
    }

    @Override
    public BasicVo updateUser(SUserVo userVo, String groups, String menus) {
        SUserExample ex = new SUserExample();
        ex.createCriteria().andUserIdEqualTo(userVo.getUserId());
        userVo.setModifyTimestamp(DateUtils.getNow());
        int i = sUserMapper.updateByExampleSelective(userVo, ex);
        if (i > 0) {
            sUserMapper.deleteUserGroup(userVo.getUserId());
            String[] group = groups.split(",");
            Arrays.stream(group).forEach(groupId -> sUserMapper.insertUserGroup(userVo.getUserId(), new Long(groupId)));
            sUserMapper.deleteUserMenu(userVo.getUserId());
            String[] menu = menus.split(",");
            Arrays.stream(menu).forEach(menuId -> sUserMapper.insertUserMenu(userVo.getUserId(), new Long(menuId)));
            return BasicVo.success("请求成功");
        } else {
            return BasicVo.fail("请求失败");
        }
    }

    @Override
    public BasicVo deleteUser(Long userId) {
        SUserExample ex = new SUserExample();
        ex.createCriteria().andUserIdEqualTo(userId);
        if (sUserMapper.deleteByExample(ex) > 0) {
            return BasicVo.success("请求成功");
        } else {
            return BasicVo.fail("请求失败");
        }
    }

    @Override
    public BasicVo getUserPage(SUserVo userVo) {
        SUserExample ex = new SUserExample();
        SUserExample.Criteria cr = ex.createCriteria();
        if (userVo.getUserName() != null) {
            cr.andUserNameLike(userVo.getUserName());
        }
        return BasicVo.success("请求成功", sUserMapper.selectByExample(ex));
    }

    @Override
    public BasicVo getSessionUserPage() {
        SUserExample ex = new SUserExample();
        SUserExample.Criteria cr = ex.createCriteria();
        cr.andSessionIdIsNotNull();
        return BasicVo.success("请求成功", sUserMapper.selectByExample(ex));
    }

    @Override
    public BasicVo createUserGroup(Long userId, Long groupId) {
        int i = sUserMapper.insertUserGroup(userId, groupId);
        if (i > 0) {
            return BasicVo.success("请求成功");
        } else {
            return BasicVo.fail("请求失败");
        }
    }

    public void truncateSesion(String sessionId) {
        SUserExample userExample = new SUserExample();
        userExample.createCriteria().andSessionIdEqualTo(sessionId);
        List<SUser> list = sUserMapper.selectByExample(userExample);
        if (list.size() > 0) {
            list.get(0).setSessionId("");
            sUserMapper.updateByExampleSelective(list.get(0), userExample);
        }
    }
}
